package com.igeek.ch02.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2022/12/8 16:41
 */
public class BaseDao<T> {

    private QueryRunner queryRunner = new QueryRunner();

    //查看单个值的方法
    public Object getSingleValue(Connection conn , String sql , Object... params) throws SQLException {
        Object obj = queryRunner.query(conn, sql, new ScalarHandler(), params);
        return obj;
    }

    //查看单个对象的方法  T
    public T getBean(Connection connection , String sql , Class<T> clazz , Object... params) throws SQLException {
        T t = queryRunner.query(connection, sql, new BeanHandler<>(clazz), params);
        return t;
    }

    //查看多个对象的方法  List<T>
    public List<T> getBeanList(Connection connection , String sql , Class<T> clazz , Object... params) throws SQLException {
        List<T> list = queryRunner.query(connection, sql, new BeanListHandler<>(clazz), params);
        return list;
    }

    //查看多表关联的数据
    public List<Map<String,Object>> getList(Connection connection , String sql , Object... params) throws SQLException {
        List<Map<String, Object>> mapList = queryRunner.query(connection, sql, new MapListHandler(), params);
        return mapList;
    }

    //增删改
    public int update(Connection connection , String sql , Object... params) throws SQLException {
        int i = queryRunner.update(connection, sql, params);
        return i;
    }
}
